﻿<%@ Page Title="" Language="C#" MasterPageFile="~/UI/Main.Master" AutoEventWireup="true" CodeBehind="xuathang.aspx.cs" Inherits="QLBH.UI.xuathang" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
     <style type="text/css">
        .popover {
            width: 276px;
        }

        .popover-title {
            padding: 0px;
        }


        .popover-content {
            max-height: 276px;
            overflow: auto;
        }

        table th {
            font-size: 16px;
        }

        #table_quyen th {
            font-size: inherit;
        }

        table tr td {
            text-align: left;
        }

        .table {
            margin-bottom: 0px;
        }
    </style>


    <div class="row">
        <div class="col-md-4">
        </div>
        <div class="col-md-4">
        </div>
        <div class="col-md-4 text-right" style="padding-bottom: 5px;">
            <span id="btn_ds_pn" data-toggle="popover" class="btn btn-primary"><span class="glyphicon glyphicon-list-alt"></span></span>
            <span id="btn_print" data-toggle="popover" class="btn btn-success"><span class="glyphicon glyphicon-print"></span></span>
            <span id="btn_add" data-toggle="popover" class="btn btn-primary">&nbsp<span class="glyphicon glyphicon-plus"></span></span>
            <span id="btn_edit" data-toggle="popover" class="btn btn-primary"><span class="glyphicon glyphicon-pencil"></span></span>
            <span id="btn_delete" data-toggle="popover" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span></span>
        </div>

    </div>
    <div class="row">
        <div class="col-md-12 text-center" id="lazyScroll" style="overflow: auto; max-height: 310px;">

            <table id="table_cart" class="table table-bordered " style="min-width: 500px;">
                <thead>
                    <tr>
                        <th class="text-center" style="width: 30px;">
                            <input id="chk_check_all" type="checkbox" value="-1" />
                        </th>
                        <th class="text-center" style="width: 50px;">STT</th>
                        <th class="hidden" style="width: 100px;">Mã SP</th>
                        <th>Tên SP </th>
                        <th class="text-center" style="width: 70px;">ĐVT</th>
                        <th class="text-center" style="width: 70px;">SL</th>
                        <th class="text-center" style="width: 100px;">Đơn Giá</th>
                        <th class="text-center" style="width: 120px;">Thành tiền</th>
                    </tr>
                </thead>
                <tbody>
                </tbody>
            </table>
        </div>
        <div class="col-md-12 text-right text-success" id="div_tong_tien" style="font-size: 25px;">0 </div>

    </div>


    <div id="popoverdsPn" style="display: none">

        <div class="form-group">
            <input type="text" class="form-control" id="txt_search_pn" placeholder="Nhập vào mã phiếu xuất" />
        </div>
        <table id="table_ds_pn" class="table table-bordered">

            <tbody>
            </tbody>
        </table>

    </div>


    <div id="popoverExampleTwoHiddenContent" style="display: none">

        <div class="form-group">
            <input type="text" class="form-control" id="txt_search" placeholder="Nhập vào tên sản phẩm" />
        </div>
        <table id="table_sanpham" class="table table-bordered">

            <tbody>
                <tr>
                    <%-- <td class="bottom-left">1</td>
                    <td style="width: 30px;"><span class="btn btn-info btn-sm"><span class="glyphicon glyphicon-trash"></span></span></td>--%>
                </tr>
            </tbody>
        </table>

    </div>

    <div id="popoverSL" style="display: none">

        <div class="form-group">
            <label for="txt_sl">Số lượng</label>
            <input type="text" class="form-control" name="txt_sl" id="txt_sl" placeholder="Số lượng" />
        </div>
        <div class="form-group">
            <label for="txt_gia_xuat">Giá xuất</label>
            <input type="text" class="form-control" name="txt_gia_xuat" id="txt_gia_xuat" onblur="this.value=formatCurrency(this.value)" placeholder="Giá nhập" />
        </div>
        <span id="btn_luu" class="btn btn-primary pull-right">&nbsp Lưu &nbsp</span>

    </div>


    <div id="popoverPN" style="display: none">

        <div class="form-group">
            <label for="cbo_kho_hang">Kho</label>
            <select class="form-control" id="cbo_kho_hang">
            </select>
        </div>

        <div class="form-group">
            <label for="cbo_khach_hang">Khách hàng</label>
            <select class="form-control" id="cbo_khach_hang">
            </select>
        </div>

        <div class="form-group">
            <label for="txt_nhan_vien">Nhân viên</label>
            <input type="text" disabled="disabled" class="form-control" name="txt_sl" id="txt_nhan_vien" placeholder="Nhân viên" />
        </div>
        <div class="form-group">
            <label for="txt_ngay_nhap">Ngày xuất</label>
            <input type="text" disabled="disabled" class="form-control" name="txt_ngay_nhap" id="txt_ngay_nhap" placeholder="Ngày nhập" />
        </div>
        <div class="form-group">
            <label for="txt_ma_px">Mã phiếu xuất</label>
            <input type="text" class="form-control" name="txt_ma_px" id="txt_ma_px" placeholder="Mã phiếu xuất" />
        </div>
        <div class="form-group">
            <label for="txt_ma_ct_goc">Mã chứng từ kèm theo</label>
            <input type="text" class="form-control" name="txt_ma_ct_goc" id="txt_ma_ct_goc" placeholder="Mã chứng từ kèm theo" />
        </div>

        <div class="form-group">
            <label for="txt_giam_gia">Giảm giá</label>
            <input type="text" class="form-control" name="txt_giam_gia" id="txt_giam_gia" onblur="this.value=formatCurrency(this.value)" placeholder="Giảm giá" value="0" />
        </div>

         <div class="form-group">
            <label for="txt_VAT">VAT(%)</label>
            <input type="text" class="form-control" name="txt_VAT" id="txt_VAT" placeholder="VAT" value="0" />
        </div>

         <div class="form-group">
            <label for="txt_con_no">Nợ lại</label>
            <input type="text" class="form-control" onblur="this.value=formatCurrency(this.value)" name="txt_con_no" id="txt_con_no" placeholder="Còn nợ" value="0" />
        </div>

        <div class="form-group">
            <label for="txt_mo_ta">Ghi chú</label>
            <textarea rows="2" class="form-control" name="txt_mo_ta" id="txt_mo_ta" placeholder="Ghi chú"></textarea>
        </div>

        <span id="btn_hoan_tat" class="btn btn-primary pull-right">&nbsp Hoàn tất &nbsp</span>

    </div>


    <!-- Popover 2 hidden title -->
    <div id="popoverExampleTwoHiddenTitle" style="display: none;">
        <h4 class="text-center">Chọn sản phẩm</h4>
    </div>


    <script src="slidebars/scripts/bootstrap/js/jquery.min.js"></script>
    <script src="slidebars/scripts/bootstrap/js/bootstrap.min.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            function Tinhtong() {
                var tables = document.getElementById("table_cart");
                var tong = 0;
                for (var i = 1; i < tables.rows.length; i++) {
                    var row = tables.rows[i]
                    tong += parseFloat(row.cells[7].innerHTML.replace(/,/g, ''));
                }

                $("#div_tong_tien").html(formatCurrency(tong));
            }

            $('body').on('click', 'span#btn_luu', function (e) {
                var tables = document.getElementById("table_cart");
                var k = -1;
                for (var i = 0; i < tables.rows.length; i++) {
                    var row = tables.rows[i]
                    if (row.className == 'info') {
                        k = i;
                        break;
                    }
                }
                if (k != -1) {

                    tables.rows[k].cells[5].innerHTML = parseInt($("#txt_sl").val().replace(/,/g, ''));
                    tables.rows[k].cells[6].innerHTML = $("#txt_gia_xuat").val();
                    tables.rows[k].cells[7].innerHTML = formatCurrency(parseInt($("#txt_sl").val().replace(/,/g, ''))
                        * parseFloat($("#txt_gia_xuat").val().replace(/,/g, '')));
                    $('#btn_edit').popover('hide');
                }
                Tinhtong();
                MakeToast('success', 'Thành công', 'Đã sửa thành công');
            });

            $('#btn_edit').on('shown.bs.popover', function () {
                var tables = document.getElementById("table_cart");
                var k = -1;
                for (var i = 0; i < tables.rows.length; i++) {
                    var row = tables.rows[i]
                    if (row.className == 'info') {
                        k = i;
                        break;
                    }
                }
                if (k != -1) {
                    $("#txt_sl").val(tables.rows[k].cells[5].innerHTML);
                    $("#txt_gia_xuat").val(tables.rows[k].cells[6].innerHTML);
                }
                else {
                    $('#btn_edit').popover('hide');
                }
            });

            function BlockUIPopover() {
                $('.popover').block({
                    message: "<img src='images/ajax-loader.gif'/>", css: { left: '50%', cursor: 'wait', backgroundColor: 'none', border: 'none', width: '50px' },
                    overlayCSS: { backgroundColor: 'none', opacity: 0.0, cursor: 'wait' }
                });
            }

            function BlockUI() {
                $.blockUI({
                    message: "<img src='images/ajax-loader.gif'/>", css: { left: '50%', cursor: 'wait', backgroundColor: 'none', border: 'none', width: '50px' },
                    overlayCSS: { backgroundColor: 'none', opacity: 0.0, cursor: 'wait' }
                });
            }


            $('body').on('keyup', 'input#txt_search', function (e) {
                if (e.keyCode == 13) {
                    e.preventDefault();
                    e.stopPropagation();
                    var search_term = $("#txt_search").val();
                    if (search_term != '') {
                        BlockUIPopover();
                        $("#table_sanpham tbody").html('');
                        var tables = document.getElementById("table_sanpham");
                        var search_term = $("#txt_search").val();
                        TimSanPham(search_term, tables.rows.length);
                    }
                    $('input#txt_search').blur();
                }
            });


            $('body').on('keyup', 'input#txt_search_pn', function (e) {
                if (e.keyCode == 13) {
                    e.preventDefault();
                    e.stopPropagation();
                    var search_term = $("#txt_search_pn").val();
                    if (search_term != '') {
                        BlockUIPopover();
                        $("#table_ds_pn tbody").html('');
                        var tables = document.getElementById("table_ds_pn");
                        var search_term = $("#txt_search_pn").val();
                        TimPhieuXuat(search_term, tables.rows.length);
                    }
                    $('input#txt_search_pn').blur();
                }
            });

            function KiemTraTonTai(ma_san_pham) {
                var tables = document.getElementById("table_cart");
                for (var i = 0; i < tables.rows.length; i++) {
                    var row = tables.rows[i]
                    if (row.cells[2].innerHTML == ma_san_pham) {
                        return i;
                    }
                }
                return -1;
            }

            function CheckTable() {
                var tables = document.getElementById("table_cart");
                var k = -1;
                for (var i = 0; i < tables.rows.length; i++) {
                    var row = tables.rows[i]
                    if (row.className == 'info') {
                        k = i;
                        break;
                    }
                }
                return k;
            }


            $('body').on('click', 'table#table_sanpham tbody tr', function (e) {

                $("#table_sanpham tbody tr").removeClass('info');
                $(this).addClass("info");
                var row = $(this);
                var index = KiemTraTonTai(row.find("td:first").html());
                if (index == -1) {
                    $("#table_cart tbody").append(
                              '<tr>' +
                              '<td><input type="checkbox" value="' + row.find("td:first").html() + '" /></td>' +
                              '<td>' + $('#table_cart tr').length + '</td>' +
                              '<td class="hidden">' + row.find("td:first").html() + '</td>' +
                              '<td>' + row.find("td:nth-child(4)").html() + '</td>' +
                              '<td>' + row.find("td:nth-child(5)").html() + '</td>' +
                              '<td class ="text-right">' + 1 + '</td>' +
                              '<td class ="text-right">' + formatCurrency(row.find("td:nth-child(3)").html()) + '</td>' +
                              '<td class ="text-right">' + formatCurrency(row.find("td:nth-child(3)").html() * 1) + '</td>' +
                              ' </tr>');
                }
                else {
                    var tables = document.getElementById("table_cart");
                    tables.rows[index].cells[5].innerHTML = parseInt(tables.rows[index].cells[5].innerHTML) + 1;
                    tables.rows[index].cells[7].innerHTML = formatCurrency(parseFloat(row.find("td:nth-child(3)").html()) * parseInt(tables.rows[index].cells[5].innerHTML.replace(/,/g, '')));
                }

                Tinhtong();
                MakeToast('success', 'Thành công', 'Đã thêm thành công');
            });


            $('body').on('click', 'table#table_ds_pn tbody tr', function (e) {

                $("#table_ds_pn tbody tr").removeClass('info');
                $(this).addClass("info");
                window.open("baocao.aspx?ma_phieu_xuat=" + $(this).find('td:not(:empty):first').html(), '_blank');
            });

            $("#chk_check_all").change(function () {

                if (this.checked) {
                    var table = document.getElementById("table_cart");
                    $('td input:checkbox', table).prop('checked', this.checked);
                }
                else {
                    var table = document.getElementById("table_cart");
                    $('td input:checkbox', table).prop('checked', '');
                }
            });

            $("#table_cart").on("click", ":checkbox", function () {
                if ($(this).val() == -1) {
                    if ($(this).is(':checked')) {
                        $("#table_cart tr").addClass("info");
                        $("#table_cart tr:first").removeClass("info");
                    }
                    else
                        $("#table_cart tr").removeClass("info");
                    return;
                }

                if ($(this).is(':checked')) {
                    $(this).parents("tr:first").addClass("info");
                }
                else {
                    $(this).parents("tr:first").removeClass("info");
                }
            });

            $("#btn_add").click(function (event) {
                event.preventDefault();

            });

            $("#btn_edit").click(function (event) {
                event.preventDefault();
                var tables = document.getElementById("table_cart");
                var k = -1;
                for (var i = 0; i < tables.rows.length; i++) {
                    var row = tables.rows[i]
                    if (row.className == 'info') {
                        k = i;
                        break;
                    }
                }
                if (k != -1) {
                    $('#btn_edit').popover('show');
                }

            });


            $("#btn_delete").click(function (event) {
                var tables = document.getElementById("table_cart");
                var k = -1;
                for (var i = 0; i < tables.rows.length; i++) {
                    var row = tables.rows[i]
                    if (row.className == 'info') {
                        k = i;
                        break;
                    }
                }
                if (k != -1) {
                    $('#btn_delete').popover('show');
                }

            });


            $('#btn_add').on('shown.bs.popover', function () {
                var h = $(window).height() - 239;
                $(".popover-content").css({ 'max-height': h });
            });

            $('#btn_ds_pn').on('shown.bs.popover', function () {
                var h = $(window).height() - 239;
                $(".popover-content").css({ 'max-height': h });
            });

            $("#btn_print").click(function (event) {
                if ($("#table_cart tbody tr").length > 0)
                    $('#btn_print').popover('show');
            });

            $("#btn_edit").popover({
                html: true,
                content: function () {
                    return $('#popoverSL').html();
                },
                title: function () {
                    return ' <h4 class="text-center">Đơn giá và Số lượng</h4>'
                },
                placement: 'bottom',
                trigger: 'Click'

            });

            $("#btn_ds_pn").popover({
                html: true,
                content: function () {
                    return $('#popoverdsPn').html();
                },
                title: function () {
                    return ' <h4 class="text-center">Danh sách phiếu xuất</h4>'
                },
                placement: 'bottom'

            });

            $("#btn_print").popover({
                html: true,
                content: function () {
                    return $('#popoverPN').html();
                },
                title: function () {
                    return ' <h4 class="text-center">Thông tin phiếu xuất</h4>'
                },
                placement: 'bottom',
                trigger: 'Click'

            });

            $('#btn_delete').on('shown.bs.popover', function () {
                var k = $('#table_cart tbody tr.info').length;
                if (k != 0) {
                    $("#msgcontent").html('Bạn có chắc muốn xóa <strong>' + k + '</strong> sản phẩm ?');
                }
            });


            function getFDate(dateObject) {

                var today = new Date(dateObject);
                if (dateObject == '') {
                    today = new Date();
                }
                var dd = today.getDate();
                var mm = today.getMonth() + 1; //January is 0!

                var yyyy = today.getFullYear();
                if (dd < 10) {
                    dd = '0' + dd
                }
                if (mm < 10) {
                    mm = '0' + mm
                }
                var today = dd + '/' + mm + '/' + yyyy;
                return today;
            }

            $('#btn_print').on('shown.bs.popover', function () {

                var k = $('#table_cart tbody tr').length;
                if (k != 0) {
                    $("#txt_ngay_nhap").val(getFDate(''));
                    $("#txt_nhan_vien").val('<%=Session["TEN_DANG_NHAP"]%>')
                }
                var h = $(window).height() - 239;
                $(".popover-content").css({ 'max-height': h });
            });

            $('body').on('click', 'span#btn_ok', function (event) {
                event.preventDefault();
                $(".info").remove();
                $("#btn_delete").popover('hide');
                Tinhtong();
                MakeToast('success', 'Thành công', 'Đã xóa thành công');
            });

            $("#btn_delete").popover({
                html: true,
                content: function () {

                    return $('#popoverConfirm').html();
                },
                title: function () {
                    return '<h4 class="text-center">Xác nhận xóa</h4>';
                },
                placement: 'left',
                trigger: 'Click'

            });

            $("#btn_add").popover({
                html: true,
                content: function () {
                    return $('#popoverExampleTwoHiddenContent').html();
                },
                title: function () {
                    return $('#popoverExampleTwoHiddenTitle').html();
                },
                placement: 'bottom'

            });


            function TimPhieuXuat(ma_phieu_xuat, tong_so_dong) {

                var DTO = {
                    'ma_phieu_xuat': ma_phieu_xuat,
                    'tong_so_dong': tong_so_dong
                };
                $.ajax({
                    type: "POST",
                    url: "../BUSINESS/Services.asmx/TimPhieuXuatTheoMa",
                    data: JSON.stringify(DTO),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        $(".popover").unblock();
                        $.each($.parseJSON(data.d), function (idx, obj) {
                            tong_so_dong += 1;
                            $("#table_ds_pn tbody").append(
                            '<tr>' +
                            ' <td class ="hidden">' + obj.MA_PHIEU_XUAT + '</td>' +
                            ' <td><b>' + obj.MA_PHIEU_XUAT + '</b><br/>' + obj.KHO_HANG.TEN_KHO_HANG + '</td>' +
                            ' <td class ="hidden">' + obj.KHO_HANG.MA_KHO_HANG + '</td>' +
                            ' </tr>');
                        });

                    },
                    error: function (data) {
                        $(".popover").unblock();
                        console.log(data.d);
                    }

                });
            }

            function TimSanPham(ten_san_pham, tong_so_dong) {

                var DTO = {
                    'ten_san_pham': ten_san_pham,
                    'tong_so_dong': tong_so_dong
                };
                $.ajax({
                    type: "POST",
                    url: "../BUSINESS/Services.asmx/TimSanPhamTheoTen",
                    data: JSON.stringify(DTO),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        $(".popover").unblock();
                        $.each($.parseJSON(data.d), function (idx, obj) {
                            tong_so_dong += 1;
                            $("#table_sanpham tbody").append(
                            '<tr>' +
                            ' <td class ="hidden">' + obj.MA_SAN_PHAM + '</td>' +
                            ' <td><b>' + obj.TEN_SAN_PHAM + '</b><br/>' + formatCurrency(obj.GIA_BAN) + '/1' + obj.DON_VI_TINH + '</td>' +
                            ' <td class ="hidden">' + obj.GIA_BAN + '</td>' +
                            ' <td class ="hidden">' + obj.TEN_SAN_PHAM + '</td>' +
                            ' <td class ="hidden">' + obj.DON_VI_TINH + '</td>' +
                            ' </tr>');
                        });

                    },
                    error: function (data) {
                        $(".popover").unblock();
                        console.log(data.d);
                    }

                });
            }

            onload = function () {
                BlockUI();
                TimKhoHang('', 0);
                TimKhachHang('', 0);
            };

            function TimKhoHang(ten_kho_hang, tong_so_dong) {

                var DTO = {
                    'ten_kho_hang': ten_kho_hang
                };
                $.ajax({
                    type: "POST",
                    url: "../BUSINESS/Services.asmx/TimKhoHangTheoTen",
                    data: JSON.stringify(DTO),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        $("#cbo_kho_hang").html('');
                        $.each($.parseJSON(data.d), function (idx, obj) {
                            $("#cbo_kho_hang").append(
                                   '<option value="' + obj.MA_KHO_HANG + '">' + obj.TEN_KHO_HANG + '</option>');
                        });

                    },
                    error: function (data) {
                        console.log(data.d);
                    }

                });
            }

            function TimKhachHang(ten_khach_hang, tong_so_dong) {

                var DTO = {
                    'ten_khach_hang': ten_khach_hang,
                    'tong_so_dong': tong_so_dong
                };
                $.ajax({
                    type: "POST",
                    url: "../BUSINESS/Services.asmx/TimKhachHangTheoTen",
                    data: JSON.stringify(DTO),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        $("#cbo_khach_hang").html('');
                        $.each($.parseJSON(data.d), function (idx, obj) {
                            $("#cbo_khach_hang").append(
                                   '<option value="' + obj.MA_KHACH_HANG + '">' + obj.TEN_KHACH_HANG + '</option>');
                        });

                    },
                    error: function (data) {
                        console.log(data.d);
                    }

                });
            }


            $('body').on('click', 'span#btn_hoan_tat', function () {

                var chi_tiet_xuat = [];
                var table = document.getElementById("table_cart");
                for (var i = 1; i < table.rows.length; i++) {
                    var nhap_hang = {
                        MA_PHIEU_XUAT: $('#txt_ma_px').val(),
                        MA_SAN_PHAM: table.rows[i].cells[2].innerHTML,
                        SO_LUONG_XUAT: table.rows[i].cells[5].innerHTML.replace(/,/g, ''),
                        GIA_XUAT: table.rows[i].cells[6].innerHTML.replace(/,/g, ''),
                        GIA_GOC: 0
                    };
                    chi_tiet_xuat[i - 1] = nhap_hang;
                }

                var phieuxuat = {
                    MA_PHIEU_XUAT: $('#txt_ma_px').val(),
                    MA_KHACH_HANG: $("#cbo_khach_hang").val(),
                    MA_KHO_HANG: $("#cbo_kho_hang").val(),
                    MA_NHAN_VIEN: 'NV0001',
                    NGAY_XUAT: new Date(),
                    SO_CHUNG_TU_GOC: $('#txt_ma_ct_goc').val(),
                    TAI_KHOAN_NO: '',
                    TAI_KHOAN_CO: '',
                    GIAM_GIA: $('#txt_giam_gia').val().replace(/,/g, ''),
                    VAT: $('#txt_VAT').val().replace(/,/g, ''),
                    SO_TIEN_NO: $('#txt_con_no').val().replace(/,/g, ''),
                    DA_TRA: 0,
                    MO_TA: $('#txt_mo_ta').val(),
                    CHITIETXUAT: chi_tiet_xuat,
                };

                var DTO = {
                    'PHIEUXUAT': phieuxuat
                };

                BlockUIPopover();
                $.ajax({
                    type: "POST",
                    url: "../BUSINESS/Services.asmx/ThemMoiPhieuXuat",
                    data: JSON.stringify(DTO),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        $(".popover").unblock();
                        var obj = jQuery.parseJSON(data.d);
                        if (obj.SUCCESS == -1) {
                            MakeToast('danger', 'Lỗi', obj.ERROR);
                        }
                        else {
                            MakeToast('success', 'Thành công', obj.ERROR);
                            $("#table_cart tbody").html('');
                            Tinhtong();
                            $("#btn_print").popover('hide');
                            window.open("baocao.aspx?ma_phieu_xuat=" + obj.MPX, '_blank');
                        }

                    },
                    error: function (data) {
                        $(".popover").unblock();
                    }

                });
            });

        });

    </script>
</asp:Content>
